/*!
  * Ronin Time Tracker v1.0 Beta
 * http://www.binn.ru
 *
 * Copyright 2011, Artur Fursa
 * Licensed under the MIT license.
 *
 * Includes jQuery JavaScript Library v1.6.2
 * http://jquery.com/
 * Copyright 2011, John Resig
 * Dual licensed under the MIT or GPL Version 2 licenses.
 *
 * Date: Fri Sep 30 21:30:00 2011 +0300
 */

var domain, token; //ronin domain, token
var updateFlag = 0; //update time or enter new
var billedFlag = 0; //load only billed time entry or all
var dataLoaded = false; //data loaded from ronin (auth OK)
var totalTime = 0; //collect time form start to submit
var collecttime = 0; //collect time from start to pause
var startTime = 0; //system time on start event
var timerStatus = false; //timer state
var oSelectedTimeZone = System.Time.currentTimeZone; //system timezone

var lWidth = 250; //undocked width
var lHeight = 265; //undocked height
var sWidth = 250; //docked width
var sHeight = 150; //docked height



function init() {
	System.Gadget.settingsUI = 'settings.html';

	if($('#domain-input').length == 0){
		System.Gadget.background = "images/bg-auth4.png"; //initial background
	}
	
	System.Gadget.onSettingsClosing = settingsClosing;
	System.Gadget.Settings.write("PrivateSetting_GadgetOpacity", 90); //set opacity to 90 percent
	System.Gadget.Settings.write("PrivateSetting_DataReload", "0"); //set reload's need to false
	
	domain = System.Gadget.Settings.readString('roninDomain'); //read domain
	token = System.Gadget.Settings.readString('roninToken'); //read token
	updateFlag = System.Gadget.Settings.readString('roninUpdate'); //read update data
	billedFlag = System.Gadget.Settings.readString('roninBilled'); //read update data
	
	if($('#domain-input').length > 0) { //set account data on setting page
		$('#domain-input').val(domain);
		$('#token-input').val(token);
		if(updateFlag == 1){
			$('#update-input').attr('checked', true);
		}
		if(billedFlag == 1){
			$('#billed-input').attr('checked', true);
		}
	}
	
	checkSettings();
}

function checkSettings() {
	domain = System.Gadget.Settings.readString('roninDomain');
	token = System.Gadget.Settings.readString('roninToken'); 
	updateFlag = System.Gadget.Settings.readString('roninUpdate');
	billedFlag = System.Gadget.Settings.readString('roninBilled');
	
	/* This section for developers that don't want input account data after reopen gadget. May be unsecure! */
	if(domain == '' && token == '') {
		domain = ''; //input your domain here
		token = ''; //input your token here
		System.Gadget.Settings.writeString('roninDomain', domain);
		System.Gadget.Settings.writeString('roninToken', token);
	}
	/* End section */
	if(domain != '' && token != '' && !dataLoaded && $('#domain-input').length == 0) {
		//get data on main gadget page
		getDataFromRonin();
	}
}

if(!dataLoaded) { //try load data from ronin
	setInterval(checkSettings, 1000);
}
function checkReload(){
	dataReload = System.Gadget.Settings.readString('PrivateSetting_DataReload');
	if(dataReload == '1') { //reload page after saving data
		System.Gadget.Settings.write("PrivateSetting_DataReload", "0");
		window.location.href = window.location.href;
	}
}
setInterval(checkReload, 1000);


//load settings on settings page
function settingsClosing(event) {
	if(dataLoaded){
		System.Gadget.background = "images/blank.png";
	}
	
	if(event.closeAction == event.Action.commit) {
		domain = $('#domain-input').val();
		token = $('#token-input').val();
		updateFlag = $('#update-input').attr('checked') ? 1 : 0;
		billedFlag = $('#billed-input').attr('checked') ? 1 : 0;

		System.Gadget.Settings.writeString('roninDomain', domain);
		System.Gadget.Settings.writeString('roninToken', token);
		System.Gadget.Settings.writeString('roninUpdate', updateFlag);
		System.Gadget.Settings.writeString('roninBilled', billedFlag);
		System.Gadget.Settings.write("PrivateSetting_DataReload", "1");
		dataLoaded = false;
	}
}

function getDataFromRonin() {
	
	//load client list
	var oReq = new window.XMLHttpRequest;
	url = 'https://' + domain + '.roninapp.com/clients?sort=date';
	oReq.open("GET", url, false, token, token);
	oReq.setRequestHeader('Accept', 'application/json');
	oReq.setRequestHeader('Content-type', 'application/json');

	oReq.onreadystatechange = function() {
		if(oReq.readyState == 4 /* complete */) {
			if(oReq.status == 200) {
				data = jQuery.parseJSON(oReq.responseText);
				
				dataStored = data;
				if(data.clients){ //ronin will change format soon
					dataStored = data.clients;
				}
				
				/*Pagination data BEGIN*/
					data.page_count = 2; // TODO change when ronin add this data
						if(data.page_count > 1) {
							for(i = 2; i <= data.page_count; i++) {
								oReq[i] = new window.XMLHttpRequest;
								page = '?page=' + i;
								url = 'https://' + domain + '.roninapp.com/clients' + page + '&sort=date';
								oReq[i].open("GET", url, false, token, token);
								oReq[i].setRequestHeader('Accept', 'application/json');
								oReq[i].setRequestHeader('Content-type', 'application/json');

								oReq[i].onreadystatechange = function() {
									if(oReq[i].readyState == 4) {
										if(oReq[i].status == 200) {
											dopData = jQuery.parseJSON(oReq[i].responseText);
										}
									}
									if(dopData){
										dopDataStored = dopData;
										if(dopData.clients){ //ronin will change format soon
											dopDataStored = dopData.clients;
										}
										if(dopDataStored) {
											for(j = 0; j < dopDataStored.length; j++) {
												dataStored.push(dopDataStored[j]);
											}
										}
									}	
								};
								oReq[i].send();
							}
						}
				/*Pagination data END*/
				//dataStored.sort(sortByName);
				optionString = '<option value="">Select client</option>';
				for( i = 0; i < dataStored.length; i++) {
					optionString += '<option value="' + dataStored[i].id + '">' + dataStored[i].name + '</option>';
				}
					$('#client-list').html(optionString);
					dataLoaded = true;
					$('#no-auth-cont').addClass('hide');
					$('#form-cont').removeClass('hide');
					$(document.body).addClass('undocked').css('width', lWidth + 'px').css('height', lHeight + 'px');
					System.Gadget.background = "images/blank.png";
			}
		}
		
	};
	oReq.send();

	//load clients project
	$('#client-list').get(0).onchange = function() {
		$('#project-list').html('<option>Select project</option>');
		$('#hours-list').html('<option value="">Select task</option>');
		var clientId = $(this).val();
		
		if(clientId != '') {
			url = 'https://' + domain + '.roninapp.com/clients/' + clientId + '/projects?page=1&sort=date';
			
			oReq.open("GET", url, false, token, token);
			oReq.setRequestHeader('Accept', 'application/json');
			oReq.setRequestHeader('Content-type', 'application/json');

			oReq.onreadystatechange = function() {
				optionString = '<option value="">Select project</option>';
				projectData = new Array();
				if(oReq.readyState == 4 /* complete */) {
					if(oReq.status == 200) {
						data = jQuery.parseJSON(oReq.responseText);
						
						if(data) {
							for( i = 0; i < data.projects.length; i++) {
								projectData.push(data.projects[i]);
							}
						}
						
						if(data.page_count > 1) {
							for(i = 2; i <= data.page_count; i++) {
								oReq[i] = new window.XMLHttpRequest;
								page = '?page=' + i;
								url = 'https://' + domain + '.roninapp.com/clients/' + clientId + '/projects' + page + '&sort=date';
								oReq[i].open("GET", url, false, token, token);
								oReq[i].setRequestHeader('Accept', 'application/json');
								oReq[i].setRequestHeader('Content-type', 'application/json');

								oReq[i].onreadystatechange = function() {
									if(oReq[i].readyState == 4) {
										if(oReq[i].status == 200) {
											dopData = jQuery.parseJSON(oReq[i].responseText);
											if(dopData) {
												for(j = 0; j < dopData.projects.length; j++) {
													projectData.push(dopData.projects[j]);
												}
											}
										}
									}
								};
								oReq[i].send();
							}
						}
					}
				}
				
				//projectData.sort(sortByName);
				for(i = 0; i < projectData.length; i++) {
					optionString += '<option value="' + projectData[i].id + '">' + projectData[i].name + '</option>';
				}
				$('#project-list').html(optionString);
			};
			oReq.send();
		} else {
			$('#project-list').html('<option>Select project</option>');
			$('#hours-list').html('<option>Select task</option>');
		}
	}
	//show old hours list
	$('#project-list').get(0).onchange = function() {
		projectId = $(this).val();
		if(projectId != '') {
			filter = billedFlag == 1 ? '?filter=unbilled' : '';
			url = 'https://' + domain + '.roninapp.com/projects/' + projectId + '/hours' + filter;
			oReq.open("GET", url, false, token, token);
			oReq.setRequestHeader('Accept', 'application/json');
			oReq.setRequestHeader('Content-type', 'application/json');

			oReq.onreadystatechange = function() {
				optionString = '<option value="">Select task</option>';

				if(oReq.readyState == 4 /* complete */) {
					if(oReq.status == 200) {
						data = jQuery.parseJSON(oReq.responseText);
						
						if(data) {
							//updateFlag
							hoursTitle = new Array(); //collect title of hours 
							hoursData = new Array();
							if(updateFlag != 1){
								for( i = 0; i < data.hours.length; i++) {
									if(jQuery.inArray(data.hours[i].title, hoursTitle) == -1){
										hoursData.push(data.hours[i]);
									}
									hoursTitle[i] = data.hours[i].title;
								}
								hoursData.sort(sortByTitle);
								optionString += '<optgroup label="Early logged hours">';
								for( i = 0; i < hoursData.length; i++) {
									optionString += '<option value="' + hoursData[i].id + '" title="' + data.hours[i].title + '">' + hoursData[i].title + '</option>';
								}
								optionString += '</optgroup>';
							} else {
								for( i = 0; i < data.hours.length; i++) {
									hoursData.push(data.hours[i]);
								}
								hoursData.sort(sortByTitle);
								optionString += '<optgroup label="Early logged hours">';
								for( i = 0; i < hoursData.length; i++) {
									dopStyle = hoursData[i]['billed?'] ? 'style="color:#BEBEBE; font-size:10px"' : '';
									optionString += '<option ' + dopStyle + ' value="' + hoursData[i].id + '" title="' + hoursData[i].title + '" rel="' + hoursData[i].hours + '">' + hoursData[i].title + ' (' + hoursData[i].hours +  ' hours)</option>';
								}
								optionString += '</optgroup>';
							}
							
							$('#hours-list').html(optionString);
						}
					}
				}
			};
			oReq.send();
		} else {
			$('#hours-list').html('<option>Select task</option>');
		}
	};
	$('#hours-list').get(0).onchange = function() {
		if($(this).val() != '') {
			$('#new-hours').val('');
		}
	};
	$('#new-hours').get(0).onkeyup = function() {
		if($(this).val() != '') {
			$('#hours-list').val('');
		}
	};
	function checkTimer() {
		if(timerStatus) {
			curTimeInfo = System.Time.getLocalTime(oSelectedTimeZone);
			curTime = Date.parse(curTimeInfo);
			collecttime = (curTime - startTime) / 1000;
			rTime = collecttime + totalTime;
			hoursv = Math.floor(rTime / 3600);
			mins = Math.floor((rTime - hoursv * 3600 ) / 60);
			sec = rTime - hoursv * 3600 - mins * 60;
			if(hoursv < 10)
				hoursv = '0' + hoursv;
			if(mins < 10)
				mins = '0' + mins;
			if(sec < 10)
				sec = '0' + sec;
			$("#hours").html(hoursv);
			$("#minutes").html(mins);
			$("#seconds").html(sec);
		}
	}

	setInterval(checkTimer, 1000);

	//Start timer
	$('#startButton').get(0).onclick = function() {
		timerStatus = true;
		sTimeInfo = System.Time.getLocalTime(oSelectedTimeZone);
		startTime = Date.parse(sTimeInfo);

		$('#startButton').addClass('hide');
		$('#pauseButton').removeClass('hide');
		$('#submitButton').addClass('hide');
		$('#clearButton').addClass('hide');
		$('#mod-time').addClass('hide');

		$('#hideFields').trigger('click');
		
		System.Sound.beep();
	}
	//Pause timer
	$('#pauseButton').get(0).onclick = function() {
		timerStatus = false;
		totalTime += collecttime;
		hoursToSubmit = Math.round(totalTime / 3.6) / 1000;
		$('#new-time').val(hoursToSubmit);

		$('#startButton').removeClass('hide');
		$('#pauseButton').addClass('hide');
		$('#submitButton').removeClass('hide');
		$('#clearButton').removeClass('hide');
		$('#mod-time').removeClass('hide');
		
		$('#showFields').trigger('click');
		
		System.Sound.beep();
	}
	//Clear timer
	$('#clearButton').get(0).onclick = function() {
		resetTimerState();
		$('#startButton').removeClass('hide');
		$('#pauseButton').addClass('hide');
	}
	//Submit data
	$('#submitButton').get(0).onclick = function() {
		projectId = $('#project-list').find('option:selected').val();
		taskHours = 0;
		if($('#new-time').val() != '' && !isNaN($('#new-time').val())) {
			taskHours = $('#new-time').val()*1;
		}
		taskTitle = '';
		if($('#hours-list').val() != '') {
			taskTitle = $('#hours-list option:selected').attr('title');
		} else {
			taskTitle = $('#new-hours').val();
		}

		if(taskTitle != '' && taskHours != 0) {
			
			if($('#hours-list').val() != '' && updateFlag == 1) { //for update time
				taskHours += $('#hours-list option:selected').attr('rel')*1;
			}
			
			dataToSend = {
				project_item : {
					hours : taskHours,
					title : taskTitle
				}
			};
			dataToSend = $.param(dataToSend);
			
			url = 'https://' + domain + '.roninapp.com/projects/' + projectId + '/hours?' + dataToSend;
			typeOfRequest = "POST";
			successText = "Time succesfully submitted";
			successHeader = 201;
			if($('#hours-list').val() != '' && updateFlag == 1) { //for update time
				url = 'https://' + domain + '.roninapp.com/hours/' + $('#hours-list').val() + '?' + dataToSend;
				typeOfRequest = "PUT";
				successText = "Time succesfully updated";
				successHeader = 200;
			}
			
			oReq.open(typeOfRequest, url, true, token, token);
			oReq.setRequestHeader('Accept', 'application/json');
			oReq.setRequestHeader('Content-type', 'application/json');

			oReq.onreadystatechange = function() {

				if(oReq.readyState == 4 /* complete */) {
					if(oReq.status == successHeader) {
						resetTimerState();
						$('#mod-time').before('<span class="system-info">' + successText + '</span>');
						$('#project-list').trigger('change'); //reload hours data

					} else {
						$('.submit-buttons').before('<span class="system-info">Some error occured. Please, try again later</span>');
					}
				}
			};
			oReq.send();
		} else {
			$('.submit-buttons').before('<span class="system-info">Select project and task before submit</span>');
		}
			setTimeout(clearMessage, 2000);
			$('.system-info').get(0).onclick = function() {
				clearMessage();
			};

		return false;
	}
	function resetTimerState(){
		timerStatus = false;
		totalTime = 0;
		$("#hours").html('00');
		$("#minutes").html('00');
		$("#seconds").html('00');
		$('#new-time').val('');
		$('#mod-time').addClass('hide');
		$('#submitButton').addClass('hide');
		$('#clearButton').addClass('hide');
	}
	//remove system message
	function clearMessage() {
		$('.system-info').hide(1000, function() {
			$('.system-info').remove();
		});
	}
	//hide select list
	$('#hideFields').get(0).onclick = function() {
		$('#hideFields').addClass('hide');
		$('#showFields').removeClass('hide');

		$('.toHide').addClass('hide');
		$(document.body).addClass('docked').css('width', sWidth + 'px').css('height', sHeight + 'px')
	}
	//show select list
	$('#showFields').get(0).onclick = function() {
		$('#hideFields').removeClass('hide');
		$('#showFields').addClass('hide');

		$('.toHide').removeClass('hide');
		$(document.body).removeClass('docked').css('width', lWidth + 'px').css('height', lHeight + 'px')
	}
	//reload gadget
	$('#reload').get(0).onclick = function() {
		window.location.href=window.location.href;
	}
}



//Sort by key title 
function sortByTitle(i, ii) {
	if (i.title > ii.title)
	return 1;
	else if (i.title < ii.title)
	return -1;
	else
	return 0;
}
//Sort by key name
function sortByName(i, ii) {
	if (i.name > ii.name)
	return 1;
	else if (i.name < ii.name)
	return -1;
	else
	return 0;
}
